(function(){
  var translations = {
    zh: {
      heading: "用户登录",
      username: "账号",
      password: "密码",
      remember: "记住我",
      language: "语言",
      login: "登录",
      error: "登录失败，请检查账号或密码。"
    },
    en: {
      heading: "User Login",
      username: "Account",
      password: "Password",
      remember: "Remember me",
      language: "Language",
      login: "Login",
      error: "Login failed. Please check your credentials."
    }
  };

  function setCookie(name, value) {
    try { document.cookie = name + "=" + encodeURIComponent(value) + "; path=/"; } catch(e) {}
  }

  function applyTranslations(lang) {
    var dict = translations[lang] || translations.zh;
    var head = document.querySelector('.ups-login-card .head');
    if (head) head.textContent = dict.heading;
    var usrInput = document.getElementById('ups-usr');
    if (usrInput) usrInput.setAttribute('placeholder', dict.username);
    var pwdInput = document.getElementById('ups-pwd');
    if (pwdInput) pwdInput.setAttribute('placeholder', dict.password);
    var rememberLabel = document.querySelector('.ups-actions label');
    if (rememberLabel) {
      var checkbox = rememberLabel.querySelector('input');
      rememberLabel.textContent = dict.remember;
      if (checkbox) rememberLabel.prepend(checkbox);
    }
    var langLabel = document.querySelector('.ups-lang');
    if (langLabel) {
      var prefix = dict.language + '：';
      var select = langLabel.querySelector('select');
      langLabel.innerHTML = '';
      var span = document.createElement('span');
      span.textContent = prefix;
      langLabel.appendChild(span);
      if (select) {
        langLabel.appendChild(select);
      }
    }
    var btn = document.querySelector('.ups-btn[type="submit"]');
    if (btn) btn.textContent = dict.login;
    var err = document.getElementById('ups-error');
    if (err && err.textContent) err.textContent = dict.error;

    // 额外：使用 flowa_i18n 的字典更新页面所有带 data-i18n 的元素
    try {
      var ft = window.flowaTranslations || {};
      var isZh = (lang || '').toLowerCase().indexOf('zh') === 0;
      function translateKey(key) {
        var entry = ft[key];
        if (!entry) return key;
        if (typeof entry === 'string') return entry;
        return isZh ? (entry.zh || entry.en || key) : (entry.en || entry.zh || key);
      }
      var nodes = document.querySelectorAll('[data-i18n]');
      nodes.forEach(function (el) {
        var key = el.getAttribute('data-i18n') || '';
        if (!key) return;
        el.textContent = translateKey(key);
      });
    } catch (e) {}
  }

  async function doLogin(e){
    e.preventDefault();
    var usr = document.getElementById('ups-usr').value.trim();
    var pwd = document.getElementById('ups-pwd').value;
    var lang = document.getElementById('ups-lang').value || 'zh';
    setCookie('preferred_language', lang);
    try { localStorage.setItem('preferred_language', lang); } catch (e) {}
    applyTranslations(lang);
    try {
      if (window.frappe && frappe.call) {
        const r = await frappe.call({ method: 'login', type: 'POST', args: { usr: usr, pwd: pwd }});
        if (!r || r.exc) throw new Error('登录失败');
        // persist and apply language right after login
        try { await frappe.call({ method: 'upsystem.upsystem.api_i18n.set_user_language', args: { language: lang } }); } catch (e) {}
        window.location.href = '/flowa';
        return;
      }
      const resp = await fetch('/api/method/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-Frappe-CSRF-Token': (window.frappe && frappe.csrf_token) || '' },
        body: JSON.stringify({ usr: usr, pwd: pwd })
      });
      if (!resp.ok) throw new Error('登录失败');
      try { await fetch('/api/method/upsystem.upsystem.api_i18n.set_user_language', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ language: lang }) }); } catch (e) {}
      window.location.href = '/flowa';
    } catch (err) {
      var el = document.getElementById('ups-error');
      if (el) {
        var dict = translations[lang] || translations.zh;
        el.textContent = dict.error;
        el.style.display = 'block';
      }
    }
  }

  var form = document.getElementById('ups-login-form');
  if (form) form.addEventListener('submit', doLogin);

  var langSelect = document.getElementById('ups-lang');
  if (langSelect && !langSelect.value) {
    langSelect.value = 'zh';
  }
  if (langSelect) {
    applyTranslations(langSelect.value || 'zh');
    langSelect.addEventListener('change', function(){
      var lang = langSelect.value || 'zh';
      setCookie('preferred_language', lang);
      try { localStorage.setItem('preferred_language', lang); } catch (e) {}
      applyTranslations(lang);
    });
  } else {
    applyTranslations('zh');
  }
})();


